package com.qf.buybook.book.service.impl;

import com.qf.buybook.book.entity.Book;
import com.qf.buybook.book.mapper.BooksDao;
import com.qf.buybook.book.service.BooksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2022-08-18
 */
@Service
@Slf4j
public class BooksServiceImpl extends ServiceImpl<BooksDao, Book> implements BooksService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean buyBook(Integer id) {
        //1. 先查看当前id的书籍是否还有剩余
        final Book book = this.getById(id);
        final Integer bookNum = book.getBookNum();
        //2. 如果还有，则抢购成功，需要把当前id的书籍的数量减1
        final int remain = bookNum - 1;
        if (bookNum>0){
            book.setBookNum(remain);
            this.updateById(book);
            log.info("抢购成功,当前书籍的剩余数量为{},抢购之后剩余{}",bookNum,remain);
            return true;
        }else {
            return false;
        }

    }
}
